import pygame
from pygame.locals import *
from phuce import settings

pygame.init()
pygame.display.init()
pygame.display.gl_set_attribute(GL_ALPHA_SIZE, 8)
pygame.display.gl_set_attribute(GL_DEPTH_SIZE, 1)
pygame.display.gl_set_attribute(GL_STENCIL_SIZE, 1)
flags = pygame.OPENGL | pygame.DOUBLEBUF
#if settings.fullscreen:
#  flags |= pygame.FULLSCREEN
pygame.display.set_mode((settings.width, settings.height), flags)

from OpenGL.GL import *
from OpenGL.GLU import *
from gameobjects.angle3 import Angle3
from gameobjects.vector3 import Vector3
from phuce.gl.shaders import Program, FragmentShader, VertexShader
from phuce import packages
from phuce.physics import Movement, Orientation
from phuce.timing import FrameTime
from phuce.view import View
from quake3.bsp import BSP46
from quake3.pk3 import PK3
from quake3 import shaders

pygame.mouse.set_visible(False)
pygame.event.set_grab(True)
pygame.time.set_timer(pygame.USEREVENT, 1000)

glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LEQUAL)
glEnable(GL_CULL_FACE)
glCullFace(GL_BACK)
glFrontFace(GL_CW)
glClearColor(0, 0, 0, 1)
glEnableClientState(GL_VERTEX_ARRAY)
glEnableClientState(GL_NORMAL_ARRAY)
glEnableClientState(GL_TEXTURE_COORD_ARRAY)

packages.add_path('baseq3')
packages.add(PK3('baseq3/pak0.pk3'))
shaders.load_scripts('scripts/')

bsp = BSP46().read(packages.open('maps/q3dm1.bsp'))
view = View(orientation=Orientation(xyz=Vector3(216, 24, -1328)))
movement = Movement(view.orientation)
trace = None

frames = 0
running = True
rot = Vector3(0.0, 0.0, 0.0)
while running:
  frames += 1
  FrameTime.update()
  for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
      if event.key == K_ESCAPE:
        running = False
    elif event.type == pygame.QUIT:
      running = False
    elif event.type == pygame.USEREVENT:
      print frames
      frames = 0

  view.orientation.backup()
  x, y = pygame.mouse.get_rel()
  view.orientation.rotate(Angle3(-x * 0.0125, -y * 0.0125, 0))
  move = Vector3()
  pressed = pygame.key.get_pressed()
  if pressed[K_w]:
    move.z -= 1
  if pressed[K_s]:
    move.z += 1
  if pressed[K_a]:
    move.x -= 1
  if pressed[K_d]:
    move.x += 1
  if pressed[K_f]:
    move.y -= 1
  if pressed[K_r]:
    move.y += 1
  move *= (pygame.key.get_mods() & KMOD_SHIFT and 800 or 400)
  movement.update(bsp, (movement.orientation.forward * move.z) + (movement.orientation.right * move.x) + (Vector3(0, 1, 0) * move.y))

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
  bsp.render(view)
  pygame.display.flip()
